package com.gzz.orchid.context.application.base.convert;

import com.gzz.orchid.common.core.tuple.TreeNode;
import com.gzz.orchid.context.application.base.pojo.DirectoryDto;
import com.gzz.orchid.context.infrastructure.persistence.entity.base.BaseDirectoryPo;

import java.util.Comparator;
import java.util.List;

/**
 * 目录树转换
 *
 * @author higmd
 */
public class BaseAssembler {
    /**
     * 目录树选项
     */
    public static List<TreeNode<Long>> mapDirectoryTreeOptions(List<BaseDirectoryPo> source, Long parentId) {
        return source.stream()
                .filter(item -> item.getParentId().equals(parentId))
                .sorted(Comparator.comparing(BaseDirectoryPo::getIdx, Comparator.reverseOrder()))
                .map(item -> {
                    var node = TreeNode.of(item.getName(), item.getId());
                    node.setChildren(BaseAssembler.mapDirectoryTreeOptions(source, item.getId()));
                    return node;
                })
                .toList();
    }

    /**
     * 目录树选项
     */
    public static List<DirectoryDto> mapDirectoryTreeDto(List<BaseDirectoryPo> source, Long parentId) {
        return source.stream()
                .filter(item -> item.getParentId().equals(parentId))
                .sorted(Comparator.comparing(BaseDirectoryPo::getIdx, Comparator.reverseOrder()))
                .map(po -> {
                    var dto = DirectoryConverter.INSTANCE.mapDto(po);
                    dto.setChildren(BaseAssembler.mapDirectoryTreeDto(source, po.getId()));
                    return dto;
                })
                .toList();
    }
}
